#coding: utf-8
# Create your views here.

from django.conf import settings
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponse,HttpResponseRedirect, HttpResponseForbidden, Http404
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST, require_GET
from django.contrib.auth.decorators import user_passes_test
from django.db.models import Avg, Max, Min, Count, Sum

from meal.forms import SignupForm, LoginForm, GuestBookForm
from meal.models import Restaurant, Course, Order, GuestBook
from meal.meal_sim import *
#import sys,os
#sys.path.append(os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]) 
#print sys.path
from similar.sim import *

from django.views.generic import list_detail
from django.views.generic.date_based import archive_today

import datetime


LOGIN_REDIRECT_URLNAME = getattr(settings, "LOGIN_REDIRECT_URLNAME", '')

def get_default_redirect(request, redirect_field_name="next",
        login_redirect_urlname=LOGIN_REDIRECT_URLNAME):
    """
    Returns the URL to be used in login procedures by looking at different
    values in the following order:
    
    - LOGIN_REDIRECT_URLNAME - the name of a URLconf entry in the settings
    - LOGIN_REDIRECT_URL - the URL in the setting
    - a REQUEST value, GET or POST, named "next" by default.
    """
    print request.user
    if request.user is not None and request.user.is_superuser:
        return settings.LOGIN_URL
    
    if login_redirect_urlname:
        default_redirect_to = reverse(login_redirect_urlname)
    else:
        default_redirect_to = settings.LOGIN_REDIRECT_URL
        print '######',default_redirect_to
    redirect_to = request.REQUEST.get(redirect_field_name)
    # light security check -- make sure redirect_to isn't garabage.
    if not redirect_to or "://" in redirect_to or " " in redirect_to:
        redirect_to = default_redirect_to
    
    return redirect_to

def login(request, form_class=LoginForm, template_name="account/login.html",
          success_url=None, url_required=False, extra_context=None):
    if extra_context is None:
        extra_context = {}

    if request.method == "POST" and not url_required:
        form = form_class(request.POST)
        if form.login(request):
            if success_url is None:
                success_url = get_default_redirect(request)
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()
    ctx = {
        "form": form,
        "url_required": url_required,
    }
    ctx.update(extra_context)
    return render_to_response(template_name, ctx,
        context_instance = RequestContext(request)
    )
    
def signup(request, form_class=SignupForm, template_name="account/signup.html", success_url=None):
        
    if success_url is None:
        success_url = get_default_redirect(request)
    if request.method == "POST":
        form = form_class(request.POST)
        if form.is_valid():
            username, password = form.save()
            user = authenticate(username=username, password=password)
            auth_login(request, user)
            request.user.message_set.create(
                message=u"您已成功登陆%(username)s。" % {'username': user.username})
            print 'success_url##########%s'%success_url
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()
    return render_to_response(template_name, {
        "form": form,
    }, context_instance=RequestContext(request))
    
@login_required
def check_order(request, template_name="check_order.html"):
        
    restaurants_list = Restaurant.objects.all()
    order_list = Order.objects.filter(user = request.user).order_by('-dt')
    aggr = Order.objects.filter(user = request.user).aggregate(avg_p = Avg('course__price'),
                                   max_p = Max('course__price'),
                                   min_p = Min('course__price'),
                                   cnt_p = Count('course__price'),
                                   sum_p = Sum('course__price'),)                                
    for k, v in aggr.iteritems():
        if v is None:
            aggr[k] = 0
    
    return render_to_response(template_name,
                              {'restaurants_list':restaurants_list,
                               'order_list':order_list,
                               'avg_p':round(aggr['avg_p'],2),
                               'max_p':aggr['max_p'],
                               'min_p':aggr['min_p'],
                               'sum_p':aggr['sum_p'],
                               'cnt_p':aggr['cnt_p']},
                              context_instance = RequestContext(request))
    
def rest_courses(request, resta_id, template_name="courses_list.html"):   

    try:
        resta = Restaurant.objects.get(id=resta_id)
        resta_name = resta.name
        course_type = resta.get_course_type_display()
        courses_list = Course.objects.filter(resta__id__exact=resta_id).order_by('-price')
    except Course.DoesNotExist:
        raise Http404

    # Use the object_list view for the heavy lifting.
    return list_detail.object_list(
        request,
        queryset = courses_list,
        template_name = template_name,
        extra_context = {"resta_name" : resta_name, 'course_type':course_type,'form':LoginForm}
    )

@login_required
@require_GET
def del_order(request, order_id):
    
    order = get_object_or_404(Order, id=order_id)
    
    if order.user == request.user or request.user.is_superuser:
        order.delete()
        request.user.message_set.create(
                message=u"%s，您已成功取消订单，%s(%s)。" % (request.user.last_name, order.course.name, order.dt.strftime('%Y-%m-%d %H:%M:%S')))
    
        return HttpResponseRedirect(reverse("check_order"))
    else:
        return HttpResponseForbidden("对不起，您没有权限删除！")
    
@login_required
@require_GET
def set_order(request, course_id, template_name="order_list.html"):
    
    course = get_object_or_404(Course,id=course_id)
    order = Order.objects.create(user=request.user, course=course)
    order.save()
            
    request.user.message_set.create(
                message=u"%s，您已订餐成功，%s(%s)。" % (request.user.last_name,course.name, order.dt.strftime('%Y-%m-%d %H:%M:%S')))
 
    #for m in request.user.message_set.all():
        #messages.append(m.message)
    #    print m.message
    
    #order_list = Order.objects.filter(user = request.user).order_by('-dt')
        
    #return render_to_response(template_name,{'order_list':order_list}, context_instance = RequestContext(request))
    return HttpResponseRedirect(reverse("check_order"))
 
@login_required
def today_order(request, template_name="order_list_today.html"):
    today = datetime.date.today()
    date_range = (datetime.datetime.combine(today, datetime.time.min), datetime.datetime.combine(today, datetime.time.max))
    order_list = Order.objects.filter(dt__range=date_range)

    resta_course_map = {}    
    for order in order_list:
            
        #有餐馆订单记录
        if resta_course_map.has_key(order.course.resta):
            #获取餐馆的订单记录
            course_cnt_rec = resta_course_map[order.course.resta]
            course_cnt_map = course_cnt_rec[0]
            resta_course_map[order.course.resta][1] = course_cnt_rec[1] + order.course.price
            #看是否订单里有这个菜
            if course_cnt_map.has_key(order.course):
                course_cnt_map.update({order.course:[course_cnt_map[order.course][0]+1, course_cnt_map[order.course][1]+order.course.price]})
            else:
                course_cnt_map[order.course] = [1,order.course.price]
        else:
            course_cnt_map = {}
            course_cnt_map[order.course] = [1,order.course.price]
            resta_course_map[order.course.resta] = [course_cnt_map,order.course.price]
    
    orders_info_dict={
        'object_list': order_list,
        'day':today,
        'resta_course_map':resta_course_map,
    }
        
    return render_to_response(template_name,
                          orders_info_dict,
                          context_instance = RequestContext(request))
    
def order_prefs(request, template_name="order_prefs.html", similarity=sim_distance):
    prefs_cnt,user_set,order_prefs = init_order_prefs()
    
    #similarity = sim_pearson
    
    order_taste_sim = {}
    for user1 in user_set:
        for user2 in user_set:
            order_taste_sim.setdefault(user1, {})            
            order_taste_sim[user1][user2] = similarity(order_prefs, user1, user2)
    
    #print order_taste_sim
    
    top_matches = topMatches(order_prefs, request.user, 5, similarity)
    
    recommendations = getRecommendations(order_prefs, request.user, similarity)
    #print recommendations
    
    itemsim = calculateSimilarItems(order_prefs, 5, similarity)
    item_recommds = getRecommendedItems(order_prefs, itemsim, request.user)
    
    return render_to_response(template_name,
                          {'prefs_cnt':prefs_cnt,
                           'order_taste_sim':order_taste_sim,
                           'user_set':user_set,
                           'top_matches':top_matches,
                           'recommendations':recommendations,
                           'item_recommds':item_recommds},
                          context_instance = RequestContext(request))
    
@login_required
def guestbook(request):
    if request.method == 'POST':
        form = GuestBookForm(request.POST)
        if form.is_valid():
            record = form.save(request.user)
            #return HttpResponse('谢谢!')
            form = GuestBookForm()
    else:
        form = GuestBookForm()
    
    message_list = GuestBook.objects.all()
    return render_to_response('guestbook.html', {'form':form, 'message_list':message_list})